<?php
global $smarty;

$thisPage = "scheduled_emails";

$params = unserialize(stripslashes(getRequestParameter("params")));

addDataservice("getschedules");
addDataservice("saveschedule");
addDataService("getscheduleinfo");

function buildLayout($smarty) {
    global $thisPage;
    global $params;
    global $titles;

    TemplateHelper::useLayout("default", true);
    $smarty->assign("default", array(
        content => getContent($smarty),
        contexthelp => getContextHelp($smarty),
    ));
}

function executeService($serviceName, $params, $smarty) {
    switch ($serviceName) {
        case "getschedules" : { return service_getschedules($params); }
        case "saveschedule" : { return service_saveschedule($params); }
        case "getscheduleinfo" : { return service_getscheduleinfo($params); }
    }
}

function service_getschedules($params) {
    Database::loadModel("tasks");
    $reccount = Database::getModel()->getEmailTaskCount();
    $tasklist = Database::getModel()->getEmailTasks(getRequestParameter("pg"), getRequestParameter("rows"));
    $limit = getRequestParameter("rows");
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount / $limit),
        records => $reccount,
        rows => JQGridHelper::convert($tasklist, "task_id"),
    );
}

function service_saveschedule($params) {
    Database::loadModel("tasks");
    if ($params['id'] == "0") {
        Database::addNew(array(
            task_type => "email",
            name => Database::getModel()->generateName($params['group'], $params['count']),
            task_date => date("Y-m-d", time() + 24*60*60),
        ));
        $id = Database::getInsertedId();
        Database::getModel()->addEmailsToTask($id, $params['group'], $params['count'], $params['subject'], $params['content']);
    } else {
        $id = $params['id'];
        Database::getModel()->updateEmailsInTask($id, $params['group'], $params['count'], $params['subject'], $params['content']);
    }
    return serviceSuccessful(array(
    ));
}

function service_getscheduleinfo($params) {
    Database::loadModel("tasks");
    $data = Database::getModel()->getEmailItemFor($params['id']);
    return serviceSuccessful($data);
}

function getContent($smarty) {
    global $thisPage;
    
    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "content", true));
}


function getcontextHelp() {
}

function getPageHeader() {
}

function getPageFooter() {
}

?>
